// filePicker.js

export async function chooseFileAndroid(callback, acceptType = "*/*") {
  if (plus.os.name !== 'Android') {
    uni.showToast({ title: '仅支持 Android APP', icon: 'none' });
    return;
  }

  const main = plus.android.runtimeMainActivity();
  const Intent = plus.android.importClass('android.content.Intent');
  const Uri = plus.android.importClass('android.net.Uri');
  const Build = plus.android.importClass('android.os.Build');
  const DocumentsContract = plus.android.importClass('android.provider.DocumentsContract');

  await requestAndroidPermissions();

  const CODE_REQUEST = 1001;
  const intent = new Intent(Intent.ACTION_GET_CONTENT);
  intent.addCategory(Intent.CATEGORY_OPENABLE);
  intent.setType(acceptType);

	main.onActivityResult = async function (requestCode, resultCode, data) {
		if (requestCode === CODE_REQUEST && resultCode === -1) {
			try {
				const uri = data.getData();
				plus.android.importClass(uri);

				const fileInfo = {
					uri: uri.toString(),
					path: null,
					mimeType: null,
					name: null
				};

				const contentResolver = main.getContentResolver();

				try {
					const cursor = plus.android.invoke(
						contentResolver,
						'query',
						uri,
						null,
						null,
						null,
						null
					);

					if (cursor) {
						plus.android.importClass(cursor);
						if (cursor.moveToFirst()) {
							const nameIndex = cursor.getColumnIndex("_display_name");
							const mimeIndex = cursor.getColumnIndex("mime_type");
							if (nameIndex >= 0) {
								fileInfo.name = cursor.getString(nameIndex);
							}
							if (mimeIndex >= 0) {
								fileInfo.mimeType = cursor.getString(mimeIndex);
							}
						}
						cursor.close();
					}
				} catch (e) {
					console.warn("内容解析失败：", e);
				}

				// ✅ 异步获取 path
				fileInfo.path = await getRealPathFromUri(main, uri);
				
				callback(fileInfo);
			} catch (e) {
				console.error("选择文件失败：", e);
				uni.showToast({ title: '文件处理失败', icon: 'none' });
			}
		}
	};


  main.startActivityForResult(intent, CODE_REQUEST);
}

function requestAndroidPermissions() {
  return new Promise((resolve, reject) => {
    plus.android.requestPermissions(
      ['android.permission.READ_EXTERNAL_STORAGE'],
      (result) => {
        if (result.deniedAlways.length > 0) {
          uni.showModal({
            title: '权限被拒绝',
            content: '请手动在设置中开启文件访问权限'
          });
          reject();
        } else {
          resolve();
        }
      },
      (error) => {
        console.error("权限申请失败:", error);
        reject();
      }
    );
  });
}

function getRealPathFromUri(context, uri) {
  return new Promise((resolve) => {
    try {
      const Build = plus.android.importClass('android.os.Build');
      const isKitKat = Build.VERSION.SDK_INT >= 19;
      const DocumentsContract = plus.android.importClass('android.provider.DocumentsContract');
      const ContentUris = plus.android.importClass('android.content.ContentUris');
      const Environment = plus.android.importClass('android.os.Environment');
      const Uri = plus.android.importClass('android.net.Uri');
      const MediaStore = plus.android.importClass('android.provider.MediaStore');

      if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        const docId = DocumentsContract.getDocumentId(uri);
        if (uri.getAuthority() === "com.android.externalstorage.documents") {
          const split = docId.split(":");
          const type = split[0];
          if (type === "primary") {
            const path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + split[1];
            return resolve(path);
          }
        } else if (uri.getAuthority() === "com.android.providers.downloads.documents") {
          const id = docId.split(":").pop();
          const contentUri = ContentUris.withAppendedId(
            Uri.parse("content://downloads/public_downloads"),
            parseInt(id)
          );
          return resolve(queryDataColumn(context, contentUri, null, null));
        } else if (uri.getAuthority() === "com.android.providers.media.documents") {
          const split = docId.split(":");
          const type = split[0];
          let contentUri = null;
          if (type === "image") contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
          else if (type === "video") contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
          else if (type === "audio") contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
          else contentUri = MediaStore.Files.getContentUri("external");

          const selection = "_id=?";
          const selectionArgs = [split[1]];
          return resolve(queryDataColumn(context, contentUri, selection, selectionArgs));
        }
      } else if (uri.getScheme() === "content") {
        return resolve(queryDataColumn(context, uri, null, null));
      } else if (uri.getScheme() === "file") {
        return resolve(uri.getPath());
      }

      resolve(null);
    } catch (err) {
      console.error("getRealPathFromUri 异常：", err);
      resolve(null);
    }
  });
}


function queryDataColumn(context, uri, selection, selectionArgs) {
  try {
    const contentResolver = context.getContentResolver();
    const cursor = plus.android.invoke(
      contentResolver,
      "query",
      uri,
      ["_data"],
      selection,
      selectionArgs,
      null
    );

    if (!cursor) return null;

    plus.android.importClass(cursor);
    let result = null;
    if (cursor.moveToFirst()) {
      const index = cursor.getColumnIndexOrThrow("_data");
      result = cursor.getString(index);
    }
    cursor.close();
    return result;
  } catch (err) {
    console.error("queryDataColumn 错误:", err);
    return null;
  }
}
